//
//  ITCropImageView.m
//  ITImageDemo
//
//  Created by Seven on 20/3/10.
//  Copyright © 2016年 Seven. All rights reserved.
//

#import "ITCropImageView.h"
#import "ITShowImageView.h"

#define WIDTH(_view) CGRectGetWidth(_view.bounds)
#define HEIGHT(_view) CGRectGetHeight(_view.bounds)
#define MAXX(_view) CGRectGetMaxX(_view.frame)
#define MAXY(_view) CGRectGetMaxY(_view.frame)
#define MINX(_view) CGRectGetMinX(_view.frame)
#define MINY(_view) CGRectGetMinY(_view.frame)
#define MID_LINE_INTERACT_WIDTH 44
#define MID_LINE_INTERACT_HEIGHT 44

#define ZoomTouchRange 1

typedef NS_ENUM(NSInteger, TKCropAreaCornerPosition) {
    TKCropAreaCornerPositionTopLeft,
    TKCropAreaCornerPositionTopRight,
    TKCropAreaCornerPositionBottomLeft,
    TKCropAreaCornerPositionBottomRight
};
typedef NS_ENUM(NSInteger, TKMidLineType) {
    
    TKMidLineTypeTop,
    TKMidLineTypeBottom,
    TKMidLineTypeLeft,
    TKMidLineTypeRight
    
};
@interface UIImage(Handler)
@end
@implementation UIImage(Handler)
- (UIImage *)imageAtRect:(CGRect)rect
{
    
    CGImageRef imageRef = CGImageCreateWithImageInRect([self CGImage], rect);
    UIImage* subImage = [UIImage imageWithCGImage: imageRef];
    CGImageRelease(imageRef);
    
    return subImage;
    
}
@end
@interface CornerView: UIView

@property (assign, nonatomic) CGFloat lineWidth;
@property (strong, nonatomic) UIColor *lineColor;
@property (assign, nonatomic) TKCropAreaCornerPosition cornerPosition;
@property (assign, nonatomic) CornerView *relativeViewX;
@property (assign, nonatomic) CornerView *relativeViewY;
@property (strong, nonatomic) CAShapeLayer *cornerShapeLayer;

- (void)updateSizeWithWidth: (CGFloat)width height: (CGFloat)height;
@end
@implementation CornerView
- (instancetype)initWithFrame:(CGRect)frame lineColor: (UIColor *)lineColor lineWidth: (CGFloat)lineWidth {
    
    self = [super initWithFrame: frame];
    if(self) {
        self.lineColor = lineColor;
        self.lineWidth = lineWidth;
    }
    return self;
}
- (void)setCornerPosition:(TKCropAreaCornerPosition)cornerPosition {

    _cornerPosition = cornerPosition;
    [self drawCornerLines];
    
}
- (void)setLineWidth:(CGFloat)lineWidth {
    
    _lineWidth = lineWidth;
    [self drawCornerLines];
    
}
- (void)drawCornerLines {
    
    if(_cornerShapeLayer && _cornerShapeLayer.superlayer) {
        [_cornerShapeLayer removeFromSuperlayer];
    }
    _cornerShapeLayer = [CAShapeLayer layer];
    _cornerShapeLayer.lineWidth = _lineWidth;
    _cornerShapeLayer.strokeColor = _lineColor.CGColor;
    _cornerShapeLayer.fillColor = [UIColor clearColor].CGColor;
    
    UIBezierPath *cornerPath = [UIBezierPath bezierPath];
    CGFloat offsetX = 0;
    CGFloat offsetY = 0;
//    if (ZoomTouchRange) {
//        offsetX = MID_LINE_INTERACT_WIDTH/2;
//        offsetY = MID_LINE_INTERACT_HEIGHT/2;
//    }
    
    CGFloat paddingX = _lineWidth / 2.0f + offsetX;
    CGFloat paddingY = _lineWidth / 2.0f + offsetY;
    switch (_cornerPosition) {
        case TKCropAreaCornerPositionTopLeft: {
            [cornerPath moveToPoint:CGPointMake(WIDTH(self), paddingY)];
            [cornerPath addLineToPoint:CGPointMake(paddingX, paddingY)];
            [cornerPath addLineToPoint:CGPointMake(paddingX, HEIGHT(self))];
            break;
        }
        case TKCropAreaCornerPositionTopRight: {
            [cornerPath moveToPoint:CGPointMake(0, paddingY)];
            [cornerPath addLineToPoint:CGPointMake(WIDTH(self) - paddingX, paddingY)];
            [cornerPath addLineToPoint:CGPointMake(WIDTH(self) - paddingX, HEIGHT(self))];
            break;
        }
        case TKCropAreaCornerPositionBottomLeft: {
            [cornerPath moveToPoint:CGPointMake(paddingX, 0)];
            [cornerPath addLineToPoint:CGPointMake(paddingX, HEIGHT(self) - paddingY)];
            [cornerPath addLineToPoint:CGPointMake(WIDTH(self), HEIGHT(self) - paddingY)];
            break;
        }
        case TKCropAreaCornerPositionBottomRight: {
            [cornerPath moveToPoint:CGPointMake(WIDTH(self) - paddingX , 0)];
            [cornerPath addLineToPoint:CGPointMake(WIDTH(self) - paddingX , HEIGHT(self) - paddingY )];
            [cornerPath addLineToPoint:CGPointMake(0, HEIGHT(self) - paddingY)];
            break;
        }
        default:
            break;
    }
    _cornerShapeLayer.path = cornerPath.CGPath;
    [self.layer addSublayer: _cornerShapeLayer];
    
}
- (void)updateSizeWithWidth: (CGFloat)width height: (CGFloat)height {
    
    switch (_cornerPosition) {
        case TKCropAreaCornerPositionTopLeft: {
            self.frame = CGRectMake(MINX(self), MINY(self), width, height);
            break;
        }
        case TKCropAreaCornerPositionTopRight: {
            self.frame = CGRectMake(MAXX(self) - width, MINY(self), width, height);
            break;
        }
        case TKCropAreaCornerPositionBottomLeft: {
            self.frame = CGRectMake(MINX(self), MAXY(self) - height, width, height);
            break;
        }
        case TKCropAreaCornerPositionBottomRight: {
            self.frame = CGRectMake(MAXX(self) - width, MAXY(self) - height, width, height);
            break;
        }
        default:
            break;
    }
    [self drawCornerLines];
    
}
- (void)setLineColor:(UIColor *)lineColor {
    
    _lineColor = lineColor;
    _cornerShapeLayer.strokeColor = lineColor.CGColor;
    
}
- (void)setFrame:(CGRect)frame{
    [super setFrame:frame];
}
@end

@interface MidLineView : UIView
@property (strong, nonatomic) CAShapeLayer *lineLayer;
@property (assign, nonatomic) CGFloat lineWidth;
@property (assign, nonatomic) CGFloat lineHeight;
@property (strong, nonatomic) UIColor *lineColor;
@property (assign, nonatomic) TKMidLineType type;
@property (strong, nonatomic) UIView *colorLine;
@property (strong, nonatomic) CALayer *colorLayer;
@end
@implementation MidLineView
- (instancetype)initWithLineWidth: (CGFloat)lineWidth lineHeight: (CGFloat)lineHeight lineColor: (UIColor *)lineColor {
    
    self = [super initWithFrame: CGRectMake(0, 0, MID_LINE_INTERACT_WIDTH, MID_LINE_INTERACT_HEIGHT)];
    if(self) {
        self.lineWidth = lineWidth;
        self.lineHeight = lineHeight;
        self.lineColor = lineColor;
        
        self.colorLine = [[UIView alloc] initWithFrame:CGRectMake(0, 0, lineWidth, lineHeight)];
        _colorLine.center = CGPointMake(MID_LINE_INTERACT_WIDTH/2, MID_LINE_INTERACT_HEIGHT/2);
        _colorLine.userInteractionEnabled = NO;
        _colorLine.backgroundColor = lineColor;
        [self addSubview:_colorLine];
        
        //_colorLine.layer.cornerRadius = _lineHeight/2;
        //[_colorLine setCornerRadius:_lineHeight/2];
        //[_colorLine setBorder:.5 color:lineColor];
    }
    return self;

}
- (void)setType:(TKMidLineType)type {

    _type = type;
    [self updateMidLine];
    
}
- (void)setLineWidth:(CGFloat)lineWidth {
    
    _lineWidth = lineWidth;
    [self updateMidLine];
    
}
- (void)setLineColor:(UIColor *)lineColor {
    _colorLine.backgroundColor = lineColor;
    _lineColor = lineColor;
    _lineLayer.strokeColor = lineColor.CGColor;
    //[_colorLine setBorder:.5 color:lineColor];
    
}
- (void)setLineHeight:(CGFloat)lineHeight {
    
    _lineHeight = lineHeight;
    _lineLayer.lineWidth = lineHeight;
    
}
- (void)setFrame:(CGRect)frame{
    CGSize oldSize = self.frame.size;
    [super setFrame:frame];
    CGSize newSize = self.frame.size;
    if (!CGSizeEqualToSize(oldSize, newSize)) {
        [self updateMidLine];
    }
}

- (void)updateMidLine{
    
    switch (_type) {
        case TKMidLineTypeTop:
        case TKMidLineTypeBottom: {
            
            CGFloat width = MAX(MIN(_lineWidth, self.frame.size.width-60), 0);
            
            _colorLine.frame = CGRectMake((self.frame.size.width-width)/2, (HEIGHT(self)-_lineHeight) / 2.0, width, _lineHeight);
            break;
        }
        case TKMidLineTypeRight:
        case TKMidLineTypeLeft: {
            
            CGFloat height = MAX(MIN(_lineWidth, self.frame.size.height-60), 0);
            _colorLine.frame = CGRectMake((WIDTH(self)-_lineHeight) / 2.0, (self.frame.size.height-height)/2, _lineHeight, height);
            break;
        }
        default:
            break;
        
    }
    _colorLine.layer.mask = [CALayer maskLayerWithCorners:UIRectCornerAllCorners radii:CGSizeMake(_lineWidth/2, _lineWidth/2) frame:_colorLine.bounds];
    //[_colorLine maskRoundCorners:UIRectCornerAllCorners radius:_lineWidth/2];
    //_colorLine.layer.cornerRadius = _lineHeight/2;
    /*return;
    switch (_type) {
        case TKMidLineTypeTop:{//
            _colorLine.frame = CGRectMake(-_lineHeight, HEIGHT(self)/2.0 -_lineHeight, WIDTH(self)+_lineHeight*2, _lineHeight);
            break;
        case TKMidLineTypeBottom: {
            _colorLine.frame = CGRectMake(-_lineHeight, HEIGHT(self)/2.0, WIDTH(self)+_lineHeight*2, _lineHeight);
            break;
        }
        case TKMidLineTypeRight:
            _colorLine.frame = CGRectMake(WIDTH(self)/2.0, -_lineHeight, _lineHeight, HEIGHT(self)+_lineHeight*2);
            break;
        case TKMidLineTypeLeft: {
            _colorLine.frame = CGRectMake(WIDTH(self)/2.0 -_lineHeight, -_lineHeight, _lineHeight, HEIGHT(self)+_lineHeight*2);
            break;
        }
        default:
            break;
        }
    }//*/
}

- (void)drawMidLine {
    
    if(_lineLayer && _lineLayer.superlayer) {
        [_lineLayer removeFromSuperlayer];
    }
    _lineLayer = [CAShapeLayer layer];
    _lineLayer.strokeColor = _lineColor.CGColor;
    _lineLayer.lineWidth = _lineHeight;
    _lineLayer.fillColor = [UIColor clearColor].CGColor;
    
    UIBezierPath *midLinePath = [UIBezierPath bezierPath];
    switch (_type) {
        case TKMidLineTypeTop:
        case TKMidLineTypeBottom: {
            [midLinePath moveToPoint:CGPointMake((WIDTH(self) - _lineWidth) / 2.0, HEIGHT(self) / 2.0)];
            [midLinePath addLineToPoint:CGPointMake((WIDTH(self) + _lineWidth) / 2.0, HEIGHT(self) / 2.0)];
            break;
        }
        case TKMidLineTypeRight:
        case TKMidLineTypeLeft: {
            [midLinePath moveToPoint:CGPointMake(WIDTH(self) / 2.0, (HEIGHT(self) - _lineWidth) / 2.0)];
            [midLinePath addLineToPoint:CGPointMake(WIDTH(self) / 2.0, (HEIGHT(self) + _lineWidth) / 2.0)];
            break;
        }
        default:
            break;
    }
    _lineLayer.path = midLinePath.CGPath;
    [self.layer addSublayer: _lineLayer];
    
}
@end

@interface CropAreaView : ITCrossView
@property (assign, nonatomic) BOOL showBorder;
@property (strong, nonatomic) UIColor *borderColor;
@property (assign, nonatomic) CGFloat borderWidth;
@property (strong, nonatomic) CAShapeLayer *borderLayer;
@property (weak, nonatomic) UIView *imageView;
@end
@implementation CropAreaView

- (instancetype)init {
    
    self = [super init];
    if(self) {
        
    }
    return self;
}
- (void)setFrame:(CGRect)frame {
    CGRect tmp = frame;
    tmp.origin.x = (int)(tmp.origin.x+0.5);
    tmp.origin.y = (int)(tmp.origin.y+0.5);
    tmp.size.width = (int)(CGRectGetMaxX(frame)+0.5) - tmp.origin.x;
    tmp.size.height = (int)(CGRectGetMaxY(frame)+0.5) - tmp.origin.y;
    [super setFrame: tmp];
    [self resetBorderLayerPath];

}
- (void)setBounds:(CGRect)bounds {
    [super setBounds:bounds];
    [self resetBorderLayerPath];
}

- (void)animationCrossLineTransparentFromRect:(CGRect)fromRect toRect:(CGRect)toRect{
    CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"path"];
    anim.duration = 0.3;
    anim.fromValue = (__bridge id _Nullable)(self.crossLineLayer.path);
    
    UIBezierPath *path = [UIBezierPath bezierPath];
    CGFloat lineNumber = self.crossLineNumber;
    CGFloat space = toRect.size.width/(lineNumber+1);
    CGFloat hegiht = toRect.size.height;
    CGFloat width = toRect.size.width;
    for (int i = 0; i<lineNumber; i++) {
        CGFloat offset = space*(i+1);
        //竖线
        [path moveToPoint:CGPointMake(offset, 0)];
        [path addLineToPoint: CGPointMake(offset, hegiht)];
        //横线
        [path moveToPoint:CGPointMake(0, offset)];
        [path addLineToPoint: CGPointMake(width, offset)];
    }
    anim.toValue = (__bridge id _Nullable)(path.CGPath);
    self.crossLineLayer.path = path.CGPath;
    anim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    [self.crossLineLayer addAnimation:anim forKey:nil];
}

#pragma mark - BorderLayer
- (void)setShowBorder:(BOOL)showBorder{
    if (_showBorder == showBorder) return;
    _showBorder = showBorder;
    if (_showBorder) {
        [self createBorderLayer];
    }else {
        [_borderLayer removeFromSuperlayer];
    }
}
- (void)createBorderLayer {
    if (!_showBorder) {
        [_borderLayer removeFromSuperlayer];
        return;
    }
    if(_borderLayer) {
        [self.layer addSublayer: _borderLayer];
        return;
    }
    _borderLayer = [CAShapeLayer layer];
    _borderLayer.fillColor = [UIColor clearColor].CGColor;
    _borderLayer.lineWidth = _borderWidth;
    _borderLayer.strokeColor = _borderColor.CGColor;
    [self.layer addSublayer: _borderLayer];
    [self resetBorderLayerPath];
}
- (void)resetBorderLayerPath {
    if (!_showBorder) return;
    UIBezierPath *layerPath = [UIBezierPath bezierPathWithRect: CGRectMake(0, 0, WIDTH(self), HEIGHT(self))];
    _borderLayer.path = layerPath.CGPath;
    
}
- (void)setBorderWidth:(CGFloat)borderWidth {
    _borderWidth = borderWidth;
    _borderLayer.lineWidth = _borderWidth;
}
- (void)setBorderColor:(UIColor *)borderColor {
    _borderColor = borderColor;
    _borderLayer.strokeColor = _borderColor.CGColor;
}

@end
@interface ITCropImageView(){
    NSInteger _lastCornnerFinger;
    CGPoint _lastCornnerPoint;
    BOOL _ignoreCrossLine;
    CGRect _lastCropRect;
}
@property (strong, nonatomic) UIView *cropMaskView;
@property (strong, nonatomic) CornerView *topLeftCorner;
@property (strong, nonatomic) CornerView *topRightCorner;
@property (strong, nonatomic) CornerView *bottomLeftCorner;
@property (strong, nonatomic) CornerView *bottomRightCorner;
@property (strong, nonatomic) CropAreaView *cropAreaView;
@property (strong, nonatomic) UIPanGestureRecognizer *topLeftPan;
@property (strong, nonatomic) UIPanGestureRecognizer *topRightPan;
@property (strong, nonatomic) UIPanGestureRecognizer *bottomLeftPan;
@property (strong, nonatomic) UIPanGestureRecognizer *bottomRightPan;
@property (strong, nonatomic) UIPanGestureRecognizer *cropAreaPan;
@property (strong, nonatomic) UIPanGestureRecognizer *imagePan;
@property (strong, nonatomic) UIPinchGestureRecognizer *cropAreaPinch;
@property (strong, nonatomic) UIPinchGestureRecognizer *imagePinch;
@property (assign, nonatomic) CGSize pinchOriSize;
@property (assign, nonatomic) CGPoint cropAreaOriCenter;
@property (assign, nonatomic) CGRect cropAreaOriFrame;
@property (strong, nonatomic) MidLineView *topMidLine;
@property (strong, nonatomic) MidLineView *leftMidLine;
@property (strong, nonatomic) MidLineView *bottomMidLine;
@property (strong, nonatomic) MidLineView *rightMidLine;
@property (strong, nonatomic) UIPanGestureRecognizer *topMidPan;
@property (strong, nonatomic) UIPanGestureRecognizer *bottomMidPan;
@property (strong, nonatomic) UIPanGestureRecognizer *leftMidPan;
@property (strong, nonatomic) UIPanGestureRecognizer *rightMidPan;
@property (assign, nonatomic) CGFloat paddingLeftRight;
@property (assign, nonatomic) CGFloat paddingTopBottom;
@property (assign, nonatomic) CGFloat imageAspectRatio;
@property (assign, nonatomic, readonly) CGFloat cornerMargin;
@property (strong, nonatomic) NSMutableArray *panGestures;

@property (nonatomic, strong) UIPanGestureRecognizer *panGesture;

@property (nonatomic, strong) BaseView *scaleView;

@end
@implementation ITCropImageView

- (instancetype)initWithFrame:(CGRect)frame {
    
    self = [super initWithFrame: frame];
    if(self) {
        [self commonInit];
    }
    return self;
    
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    
    self = [super initWithCoder: aDecoder];
    if(self) {
        [self commonInit];
    }
    return self;
    
}
- (void)commonInit {
    
    //self.backgroundColor = COLOR_3c3c3c;
    [self setUp];
    //[self createCorners];
    [self resetCropAreaOnCornersFrameChanged];
    //[self bindPanGestures];
    
}
- (void)dealloc {
    
    [_cropAreaView removeObserver: self forKeyPath: @"frame"];
    [_cropAreaView removeObserver: self forKeyPath: @"center"];
    
}
- (void)setBackgroundColor:(UIColor *)backgroundColor{
    [super setBackgroundColor:backgroundColor];
    _imageView.backgroundColor = backgroundColor;
}
- (void)setUp {
    _contentChangeEnable = YES;
    
    self.panGestures = [NSMutableArray array];
    _imageView = [[ITShowImageView alloc]initWithFrame: self.bounds];
    _imageView.contentMode = UIViewContentModeScaleAspectFill;
    _imageView.clipsToBounds = NO;
    _imageView.userInteractionEnabled = YES;
    _imageView.cropChangeEnable = YES;
    //_imageView.shouldRotate = NO;
    //_imageView.scaleChangeEnableInRotation = YES;
    _imageView.cropView = self;
    _imageAspectRatio = 0;
    [self addSubview: _imageView];
    
    _cropMaskView = [[UIView alloc]initWithFrame: _imageView.frame];
    _cropMaskView.userInteractionEnabled = NO;
    _cropMaskView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
    _cropMaskView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [self addSubview: _cropMaskView];
    
    UIColor *defaultColor = [UIColor colorWithWhite:1 alpha:0.5];
    _cropAreaBorderLineColor = defaultColor;
    _cropAreaCornerLineColor = defaultColor;
    _cropAreaBorderLineWidth = 3;
    _cropAreaCornerLineWidth = 3;
    _cropAreaCornerWidth = 13;
    _cropAreaCornerHeight = 13;
    _cropAspectRatio = 0;
    _minSpace = 30;
    
    _tmpCornerMargin = 20;
    
    _cropAreaCrossLineWidth = .5;
    _cropAreaCrossLineColor = defaultColor;
    
    _cropAreaMidLineWidth = 60;
    _cropAreaMidLineHeight = 3;
    _cropAreaMidLineColor = defaultColor;
    
    _cropAreaView = [[CropAreaView alloc] init];
    _cropAreaView.userInteractionEnabled = NO;
    
    //*
    _cropAreaView.borderWidth = _cropAreaBorderLineWidth;
    _cropAreaView.borderColor = _cropAreaBorderLineColor;
    _cropAreaView.crossLineColor = _cropAreaCrossLineColor;
    _cropAreaView.crossLineWidth = _cropAreaCrossLineWidth;
    //*/
    
    _cropAreaView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [self addSubview: _cropAreaView];
    _cropAreaView.imageView = _imageView;
    
    [_cropAreaView addObserver: self
                    forKeyPath: @"frame"
                       options: NSKeyValueObservingOptionNew | NSKeyValueObservingOptionInitial
                       context: NULL];
    [_cropAreaView addObserver: self
                    forKeyPath: @"center"
                       options: NSKeyValueObservingOptionNew | NSKeyValueObservingOptionInitial
                       context: NULL];
    
}


- (CGRect)cropAreaFrame{
    return _cropAreaView.frame;
}

- (void)setImageViewFrame:(CGRect)rect{//居中
    [self updateCropViewFrame:rect cropAspectRatio:_cropAspectRatio];
    [_imageView.zoomScrollView setZoomScale:_imageView.zoomScrollView.minimumZoomScale];
    [_imageView moveImageToCenterWithAnimation:NO];
}

- (void)updateCropViewFrame:(CGRect)rect cropAspectRatio:(CGFloat)cropAspectRatio{
    _cropAspectRatio = cropAspectRatio;
    if (_cycleMaskEnable) {
        _cycleWidth = rect.size.width;
    }
    _cropAreaView.frame = rect;
    [self autoAdjustViews];
    
    [self resetCornersOnCropAreaFrameChanged];
    //去掉animation;
    [self resetCropTransparentArea];
}

- (void)autoAdjustViews{
    [self setOtherPanGestureEnable:YES gesture:nil];
    if (!_contentChangeEnable) {
        return;
    }
    CGRect cropRect = _cropAreaView.frame;
    if (!_autoScaleCenter) {
        /*//超出边界移回
        if (cropRect.origin.x<0) {
            cropRect.origin.x=0;
        }
        if (cropRect.origin.y<0) {
            cropRect.origin.y=0;
        }//*/
        
        //BOOL  hasRotation = CGAffineTransformGetRotation(_imageView.transform) != 0;
        CGRect  lastScrollRect = _imageView.zoomScrollView.frame;
        __block CGPoint offset = _imageView.zoomScrollView.contentOffset;
        //__block CGPoint offset = CGPointMake(cropRect.origin.x-_imageView.zoomScrollView.left, cropRect.origin.y-_imageView.zoomScrollView.top);
        
        //offset.x += _imageView.zoomScrollView.contentOffset.x;
        //offset.y += _imageView.zoomScrollView.contentOffset.y;
        
        [_imageView updateCropRect:cropRect reset:NO change:^{
            
            CGRect  theScrollRect = _imageView.zoomScrollView.frame;
            CGFloat currScale = _imageView.zoomScrollView.zoomScale;
            CGFloat scaleX = _imageView.zoomImageView.frame.size.width/theScrollRect.size.width;
            CGFloat scaleY = _imageView.zoomImageView.frame.size.height/theScrollRect.size.height;
            _imageView.zoomScrollView.minimumZoomScale = currScale / MIN(scaleX, scaleY);
            
            scaleX = self.frame.size.width/_imageView.zoomImageView.width;
            scaleY = self.frame.size.height/_imageView.zoomImageView.frame.size.height;
            _imageView.zoomScrollView.maximumZoomScale = currScale * MAX(scaleY, scaleX) * 3;
            
            
            offset.x += _imageView.zoomScrollView.frame.origin.x-lastScrollRect.origin.x;
            offset.y += _imageView.zoomScrollView.frame.origin.y-lastScrollRect.origin.y;
            
            offset.x = MAX(0, offset.x);
            offset.y = MAX(0, offset.y);
            
            CGFloat tmpx = offset.x + _imageView.zoomScrollView.frame.size.width -  _imageView.zoomImageView.frame.size.width;
            if (tmpx > 0) {
                offset.x -= tmpx;
            }
            CGFloat tmpy = offset.y + _imageView.zoomScrollView.frame.size.height -  _imageView.zoomImageView.frame.size.height;
            if (tmpy > 0) {
                offset.y -= tmpy;
            }
            [_imageView.zoomScrollView setContentOffset:offset animated:NO];
        }];
        return;
    }
    
    
    CGRect willRect = self.cropAreaViewWillFrame;
    CGFloat scale = willRect.size.width/cropRect.size.width;
    
    [self animationCropTransparentAreaFromRect:cropRect toRect:willRect];
    //_imageView.zoomScrollView.minimumZoomScale /= scale;
    CGFloat zoomScale = _imageView.zoomScrollView.zoomScale*scale;
    
    CGPoint offset = _imageView.zoomScrollView.contentOffset;
    CGPoint point = _cropAreaOriFrame.origin;//image当前位置
    //fromPoint to
    //CGPoint fromPoint = [self convertPoint:cropRect.origin toView:_imageView.zoomScrollView];
    
    //fromPoint = cropRect.origin;
    //toPoint = _cropAreaOriFrame.origin;
    
    //offset.x += (fromPoint.x - toPoint.x);
    //offset.y += (fromPoint.y - toPoint.y);
    
    offset.x += (cropRect.origin.x - point.x);
    offset.y += (cropRect.origin.y - point.y);
    
    //CGFloat rotate = CGAffineTransformGetRotation(_imageView.zoomScrollView.transform);
    //CGFloat wh = atan(_imageView.zoomScrollView.bounds.size.height/_imageView.zoomScrollView.bounds.size.width);
    //CGFloat angle = wh+rotate;
    
    offset.x *= scale;
    offset.y *= scale;

    //*
    CGSize contentSize = _imageView.zoomScrollView.contentSize;
    contentSize.height *= scale;
    contentSize.width *= scale;
    offset.x = MIN(MAX(0, offset.x), contentSize.width-willRect.size.width);
    offset.y = MIN(MAX(0, offset.y), contentSize.height-willRect.size.height);
    //*/
    
    [UIView animateWithDuration:0.3 animations:^{
        _cropAreaView.frame = willRect;
        [self resetCornersOnCropAreaFrameChanged];
        
        //改变图片frame  放大居中
        [_imageView updateCropRect:willRect reset:NO change:^{
            
            [_imageView.zoomScrollView setZoomScale:zoomScale animated:NO];
            [_imageView.zoomScrollView setContentOffset:offset animated:NO];
        }];
        //_imageView.frame = imageWillRect;
        
        //[self resetCropTransparentArea];
    } completion:^(BOOL finished) {
        if (_cropAspectRatio == 0) {
            //自由模式下 需要改变miniScale
            CGFloat currScale = _imageView.zoomScrollView.zoomScale;
            CGSize contentSize = _imageView.zoomScrollView.contentSize;
            
            CGFloat tmpWS = willRect.size.width/contentSize.width;
            CGFloat tmpHS = willRect.size.height/contentSize.height;
            CGFloat minScale = MAX(tmpWS, tmpHS)*currScale;
            _imageView.zoomScrollView.minimumZoomScale = minScale;
        }
    }];
}

- (void)autoScaleImageView:(BOOL)amimation{
    
    //CGRect imageRect = [_imageView.zoomScrollView convertRect:_imageView.zoomImageView.frame toView:self];
    CGRect imageRect = _lastCropRect;
    CGRect cropRect = _cropAreaView.frame;
    CGFloat scaleWidth = cropRect.size.width/imageRect.size.width;
    CGFloat scaleHeight = cropRect.size.height/imageRect.size.height;
    CGFloat maxScale = MAX(scaleWidth, scaleHeight);
    GKLOG(@"scaleWidth=%f scaleH=%f max = %f", scaleWidth, scaleHeight, maxScale);
    CGRect lastRect = _imageView.zoomScrollView.frame;

    CGPoint offset = _imageView.zoomScrollView.contentOffset;
    
    //_imageView.zoomScrollView.frame = cropRect;
    offset.x += cropRect.origin.x - lastRect.origin.x;
    offset.y += cropRect.origin.y - lastRect.origin.y;
    _imageView.zoomScrollView.minimumZoomScale = 0.01;
    _imageView.zoomScrollView.maximumZoomScale = 100;
    
    GKLOG(@"1111=%@ scale=%f",NSStringFromCGPoint(_imageView.zoomScrollView.contentOffset),_imageView.zoomScrollView.zoomScale);
    _imageView.zoomScrollView.zoomScale = _imageView.zoomScrollView.zoomScale*maxScale;
    //_imageView.zoomScrollView.contentOffset = offset;
    GKLOG(@"2222=%@ scale=%f",NSStringFromCGPoint(_imageView.zoomScrollView.contentOffset),_imageView.zoomScrollView.zoomScale);

    _lastCropRect = cropRect;
}

- (void)autoAdjustImageView:(BOOL)animation{
    if (!_autoScale) {
        //return;
    }
    _currCropAspectRatio = _cropAreaView.frame.size.width/_cropAreaView.frame.size.height;
    //return;
    
    CGRect imageRect = [_imageView.zoomScrollView convertRect:_imageView.zoomImageView.frame toView:_imageView];
    
    CGRect cropRect = [self convertRect:_cropAreaView.frame toView:_imageView];
    
    if (_cycleMaskEnable) {
        cropRect = _cropAreaView.frame;
    }
    
    //边界限制.
    CGFloat tmpOffset = .01;
    CGRect tmpRect = imageRect;
    tmpRect.origin.x -= tmpOffset;
    tmpRect.origin.y -= tmpOffset;
    tmpRect.size.width += tmpOffset;
    tmpRect.size.height += tmpOffset;
    if (CGRectContainsRect(tmpRect, cropRect)) {
        //没有超出边界 不用处理
        return;
    }
    
    CGFloat scaleWidth = cropRect.size.width/imageRect.size.width;
    CGFloat scaleHeight = cropRect.size.height/imageRect.size.height;
    CGFloat maxScale = MAX(scaleWidth, scaleHeight);
    if (maxScale > 1) {
        //maxScale = _imageView.zoomScrollView.zoomScale*maxScale;
    }
    //基于image 相对frame 和 cropRect 偏移 改变frame
    CGRect toRect = _imageView.zoomScrollView.frame;
    CGFloat offsetX = cropRect.origin.x - imageRect.origin.x;
    if (offsetX < 0) {
        toRect.origin.x += offsetX;
    }else {
        CGFloat offsetW = CGRectGetMaxX(cropRect) - CGRectGetMaxX(imageRect);
        if (offsetW > 0) {
            toRect.origin.x += offsetW;
        }
    }
    CGFloat offsetY = cropRect.origin.y - imageRect.origin.y;
    if (offsetY < 0) {
        toRect.origin.y += offsetY;
    }else {
        CGFloat offsetH = CGRectGetMaxY(cropRect)-CGRectGetMaxY(imageRect);
        if (offsetH > 0) {
            toRect.origin.y += offsetH;
        }
    }
    if (maxScale<=1 && !animation) {
        _imageView.zoomScrollView.frame = toRect;
    }else {
        CGFloat amimationTime = animation ? .3 : 0.1;
        [UIView animateWithDuration:amimationTime animations:^{
            _imageView.zoomScrollView.frame = toRect;
            if (maxScale>1) {
                _imageView.zoomScrollView.zoomScale = _imageView.zoomScrollView.zoomScale*maxScale;
            }
        }];
    }
}
#pragma mark - PanGesture Bind
- (void)bindPanGestures {
    
    _topLeftPan = [[UIPanGestureRecognizer alloc]initWithTarget: self action: @selector(handleCornerPan:)];
    _topRightPan = [[UIPanGestureRecognizer alloc]initWithTarget: self action: @selector(handleCornerPan:)];
    _bottomLeftPan = [[UIPanGestureRecognizer alloc]initWithTarget: self action: @selector(handleCornerPan:)];
    _bottomRightPan = [[UIPanGestureRecognizer alloc]initWithTarget: self action: @selector(handleCornerPan:)];
    //_cropAreaPan = [[UIPanGestureRecognizer alloc]initWithTarget: self action: @selector(handleCropAreaPan:)];
    //_imagePan = [[UIPanGestureRecognizer alloc]initWithTarget: self action: @selector(handleImagePan:)];
    
    [_topLeftCorner addGestureRecognizer: _topLeftPan];
    [_topRightCorner addGestureRecognizer: _topRightPan];
    [_bottomLeftCorner addGestureRecognizer: _bottomLeftPan];
    [_bottomRightCorner addGestureRecognizer: _bottomRightPan];
    //[_cropAreaView addGestureRecognizer: _cropAreaPan];
    //[self addGestureRecognizer:_imagePan];
    
    [_panGestures addObject:_topLeftPan];
    [_panGestures addObject:_topRightPan];
    [_panGestures addObject:_bottomLeftPan];
    [_panGestures addObject:_bottomRightPan];
}

- (void)setOtherPanGestureEnable:(BOOL)enable gesture:(UIGestureRecognizer *)pan{
    [_panGestures enumerateObjectsUsingBlock:^(UIGestureRecognizer * obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj != pan) {
            obj.enabled = enable;
        }
    }];
    //_imageView.userInteractionEnabled = enable;
}

#pragma mark - PinchGesture CallBack
- (void)handleImagePinch: (UIPinchGestureRecognizer *)sender {
    
    static CGFloat lastScale;
    static CGFloat lastWidth;
    static CGFloat lastHeight;
    CGFloat curScale = sender.scale;
    switch (sender.state) {
        case UIGestureRecognizerStateBegan:{
            lastScale = curScale;
            lastWidth = _imageView.bounds.size.width;
            lastHeight = _imageView.bounds.size.height;
        }
            break;
        case UIGestureRecognizerStateChanged:{
            
            CGFloat offsetScale = curScale - lastScale + 1;
            
            CGFloat toWidth = offsetScale * lastWidth;
            CGFloat toHeight =offsetScale * lastHeight;
            
            _imageView.bounds = CGRectMake(0, 0, toWidth, toHeight);
            
        }
            break;
        case UIGestureRecognizerStateEnded:{
            [self autoAdjustImageView:YES];
        }
            break;
            
        default:
            break;
    }
    
}

- (void)handleCropAreaPinch: (UIPinchGestureRecognizer *)pinchGesture {
    
    switch (pinchGesture.state) {
        case UIGestureRecognizerStateBegan: {
            _pinchOriSize = _cropAreaView.frame.size;
            break;
        }
        case UIGestureRecognizerStateChanged: {
            [self resetCropAreaByScaleFactor: pinchGesture.scale];
            break;
        }
        case UIGestureRecognizerStateEnded: {
            [self autoAdjustImageView:YES];
            [self autoAdjustViews];
            break;
        }
        default:
            break;
    }
    
}
#pragma mark - PanGesture CallBack

- (void)handleImagePan: (UIPanGestureRecognizer *)sender {
    static NSInteger lastFinger;
    static CGPoint lastPoint;
    static CGPoint lastCenter;
    CGPoint curPoint = [sender locationInView:self.superview];
    switch (sender.state) {
        case UIGestureRecognizerStateBegan:{
            lastPoint = curPoint;
            lastCenter = _imageView.center;
            lastFinger = sender.numberOfTouches;
            //禁用其他手势
        }
            break;
        case UIGestureRecognizerStateChanged:{
            if (lastFinger != sender.numberOfTouches) {
                lastPoint = curPoint;
                lastCenter = _imageView.center;
                lastFinger = sender.numberOfTouches;
                //break;
            }
            CGPoint toPoint = _imageView.center;
            toPoint.x = lastCenter.x + curPoint.x - lastPoint.x;
            toPoint.y = lastCenter.y + curPoint.y - lastPoint.y;
            _imageView.center = toPoint;
        }
            break;
        case UIGestureRecognizerStateEnded:{
            [self autoAdjustImageView:YES];
        }
            break;
            
        default:
            break;
    }
}

- (void)handleCropAreaPan: (UIPanGestureRecognizer *)panGesture {
    
    switch (panGesture.state) {
        case UIGestureRecognizerStateBegan: {
            _cropAreaOriFrame = _cropAreaView.frame;
            _cropAreaOriCenter = _cropAreaView.center;
            [self setOtherPanGestureEnable:NO gesture:panGesture];
            break;
        }
        case UIGestureRecognizerStateChanged: {
            CGPoint translation = [panGesture translationInView: _imageView];
            CGPoint willCenter = CGPointMake(_cropAreaOriCenter.x + translation.x, _cropAreaOriCenter.y + translation.y);
            CGFloat centerMinX = WIDTH(_cropAreaView) / 2.0f + self.tmpCornerMargin ;
            CGFloat centerMaxX = WIDTH(_imageView) - WIDTH(_cropAreaView) / 2.0f - self.tmpCornerMargin;
            CGFloat centerMinY = HEIGHT(_cropAreaView) / 2.0f + self.tmpCornerMargin;
            CGFloat centerMaxY = HEIGHT(_imageView) - HEIGHT(_cropAreaView) / 2.0f - self.tmpCornerMargin;
            _cropAreaView.center = CGPointMake(MIN(MAX(centerMinX, willCenter.x), centerMaxX), MIN(MAX(centerMinY, willCenter.y), centerMaxY));
            [self resetCornersOnCropAreaFrameChanged];
            break;
        }
        case UIGestureRecognizerStateEnded: {
            [self autoAdjustViews];
            break;
        }
        default:
            break;
    }
  
}
- (void)handleMidPan: (UIPanGestureRecognizer *)panGesture {
    
    MidLineView *midLineView = (MidLineView *)panGesture.view;
    
    static CGPoint __lastPoint;
    
    CGPoint translation = [panGesture translationInView:self];
    
    switch (panGesture.state) {
        case UIGestureRecognizerStateBegan: {
            //self.showCrossLines = YES;
            
            __lastPoint = translation;
            
            _cropAreaOriFrame = _cropAreaView.frame;
            
            [self setOtherPanGestureEnable:NO gesture:panGesture];
            
            //[_cropAreaView setShowBorder:YES];
            break;
        }
        case UIGestureRecognizerStateChanged: {
            
            CGRect willFrame = _cropAreaOriFrame;
            
            switch (midLineView.type) {
                case TKMidLineTypeTop: {
                    CGFloat offset = translation.y - __lastPoint.y;
                    
                    CGFloat minHeight = _minSpace;// + (_cropAreaCornerHeight - _cropAreaCornerLineWidth + _cropAreaBorderLineWidth) * 2;
                    CGFloat maxHeight = CGRectGetMaxY(_cropAreaOriFrame);// - (_cropAreaCornerLineWidth - _cropAreaBorderLineWidth);
                    CGFloat willHeight = MIN(MAX(minHeight, CGRectGetHeight(_cropAreaOriFrame) - offset), maxHeight);
                    
                    CGFloat deltaY = willHeight - CGRectGetHeight(_cropAreaOriFrame);
                    
                    if (_cropAspectRatio == 0) {
                        willFrame.origin.y = maxHeight-willHeight;
                        willFrame.size.height = willHeight;
                    }else {
                        CGFloat width = _cropAspectRatio*willHeight;
                        if (width < minHeight) {
                            width = minHeight;
                            willHeight = width/_cropAspectRatio;
                        }
                        
                        willFrame = CGRectMake(CGRectGetMinX(_cropAreaOriFrame)+ (_cropAreaOriFrame.size.width-width)/2, CGRectGetMinY(_cropAreaOriFrame) - deltaY, width, willHeight);
                    }
                    
                    break;
                }
                case TKMidLineTypeBottom: {
                    CGFloat offset = translation.y - __lastPoint.y;
                    
                    CGFloat minHeight = _minSpace ;//+ (_cropAreaCornerHeight - _cropAreaCornerLineWidth + _cropAreaBorderLineWidth) * 2;
                    CGFloat maxHeight = HEIGHT(self) - CGRectGetMinY(_cropAreaOriFrame);// - (_cropAreaCornerLineWidth - _cropAreaBorderLineWidth);
                    CGFloat willHeight = MIN(MAX(minHeight, CGRectGetHeight(_cropAreaOriFrame) + offset), maxHeight);
                    if (_cropAspectRatio == 0) {
                        willFrame.size.height = willHeight;
                    }else {
                        CGFloat width = _cropAspectRatio*willHeight;
                        if (width < minHeight) {
                            width = minHeight;
                            willHeight = width/_cropAspectRatio;
                        }
                        
                        willFrame = CGRectMake(CGRectGetMinX(_cropAreaOriFrame)+ (_cropAreaOriFrame.size.width-width)/2, CGRectGetMinY(_cropAreaOriFrame), width, willHeight);
                        
                    }
                    break;
                }
                case TKMidLineTypeLeft: {
                    CGFloat offset = translation.x - __lastPoint.x;
                    
                    CGFloat minWidth = _minSpace;// + (_cropAreaCornerWidth - _cropAreaCornerLineWidth + _cropAreaBorderLineWidth) * 2;
                    CGFloat maxWidth = CGRectGetMaxX(_cropAreaOriFrame);// - (_cropAreaCornerLineWidth - _cropAreaBorderLineWidth);
                    CGFloat willWidth = MIN(MAX(minWidth, CGRectGetWidth(_cropAreaOriFrame) - offset), maxWidth);
                    CGFloat deltaX = willWidth - CGRectGetWidth(_cropAreaOriFrame);
                    if (_cropAspectRatio == 0) {
                        willFrame.origin.x = maxWidth-willWidth;
                        willFrame.size.width = willWidth;
                    }else {
                        CGFloat height = willWidth/_cropAspectRatio;
                        if (height < minWidth) {
                            height = minWidth;
                            willWidth = height*_cropAspectRatio;
                        }
                        willFrame = CGRectMake(CGRectGetMinX(_cropAreaOriFrame) - deltaX, CGRectGetMinY(_cropAreaOriFrame)+ (_cropAreaOriFrame.size.height-height)/2, willWidth, height);
                        
                    }
                    break;
                }
                case TKMidLineTypeRight: {
                    CGFloat offset = translation.x - __lastPoint.x;
                    
                    CGFloat minWidth = _minSpace;// + (_cropAreaCornerWidth - _cropAreaCornerLineWidth + _cropAreaBorderLineWidth) * 2;
                    CGFloat maxWidth = WIDTH(self) - CGRectGetMinX(_cropAreaOriFrame);// - (_cropAreaCornerLineWidth - _cropAreaBorderLineWidth);
                    CGFloat willWidth = MIN(MAX(minWidth, CGRectGetWidth(_cropAreaOriFrame) + offset), maxWidth);
                    if (_cropAspectRatio == 0) {
                        willFrame.size.width = willWidth;
                    }else {
                        CGFloat height = willWidth/_cropAspectRatio;
                        if (height < minWidth) {
                            height = minWidth;
                            willWidth = height*_cropAspectRatio;
                        }
                        
                        willFrame = CGRectMake(CGRectGetMinX(_cropAreaOriFrame), CGRectGetMinY(_cropAreaOriFrame)+ (_cropAreaOriFrame.size.height-height)/2, willWidth, height);
                    }
                    break;
                }
                default:
                    break;
            }
            /*
            CGFloat left = [self getChangeOffsetWithOffset:CGRectGetMinX(willFrame)];
            CGFloat right = [self getChangeOffsetWithOffset:CGRectGetMaxX(willFrame)];
            CGFloat top = [self getChangeOffsetWithOffset:CGRectGetMinY(willFrame)];
            CGFloat bottom = [self getChangeOffsetWithOffset:CGRectGetMaxY(willFrame)];
            
            //willFrame = CGRectMake(left, top, right-left, bottom-top);
            /*/
            _cropAreaView.frame = willFrame;
            
            [self resetCornersOnCropAreaFrameChanged];
            [self autoAdjustImageView:NO];
            [self resetCropTransparentArea];
            break;
        }
        case UIGestureRecognizerStateEnded: {
            CGRect willFrame = _cropAreaView.frame;
            
            CGFloat left = [self getChangeOffsetWithOffset:CGRectGetMinX(willFrame)];
            CGFloat right = [self getChangeOffsetWithOffset:CGRectGetMaxX(willFrame)];
            CGFloat top = [self getChangeOffsetWithOffset:CGRectGetMinY(willFrame)];
            CGFloat bottom = [self getChangeOffsetWithOffset:CGRectGetMaxY(willFrame)];
            
            willFrame = CGRectMake(left, top, right-left, bottom-top);
            
            _cropAreaView.frame = willFrame;
            
            [self autoAdjustImageView:NO];
            [self resetCropTransparentArea];
            
            [self autoAdjustViews];
            
            self.showCrossLines = NO;
            [_cropAreaView setShowBorder:NO];
            break;
        }
        default:
            break;
    }
}
- (void)handleCornerPan: (UIPanGestureRecognizer *)panGesture {
    
    CornerView *panView = (CornerView *)panGesture.view;
    CornerView *relativeViewX = panView.relativeViewX;
    CornerView *relativeViewY = panView.relativeViewY;
    CGPoint curPoint = [panGesture locationInView:self];
    static CGPoint _lastCornnerOffset;
    switch (panGesture.state) {
        case UIGestureRecognizerStateBegan:{
            _cropAreaOriFrame = _cropAreaView.frame;
            self.showCrossLines = YES;
            _lastCornnerOffset = CGPointMake(curPoint.x - panView.center.x, curPoint.y-panView.center.y);
            _lastCornnerPoint = CGPointMake(relativeViewY.center.x, relativeViewX.center.y);
            _lastCornnerFinger = panGesture.numberOfTouches;
        }
            break;
        case UIGestureRecognizerStateChanged:{
            if (_lastCornnerFinger != panGesture.numberOfTouches) {
                _lastCornnerOffset = CGPointMake(curPoint.x - panView.center.x, curPoint.y-panView.center.y);
                _lastCornnerPoint = CGPointMake(relativeViewY.center.x, relativeViewX.center.y);
                _lastCornnerFinger = panGesture.numberOfTouches;
                //break;
            }
            CGFloat tmpWidth = _cropAreaCornerWidth ;
            CGFloat tmpHeight = _cropAreaCornerHeight ;
            
//            if (ZoomTouchRange) {
//                tmpWidth += MID_LINE_INTERACT_WIDTH/2;
//                tmpHeight += MID_LINE_INTERACT_HEIGHT/2;
//            }
            
            CGFloat minSpace = _minSpace;
            NSInteger xFactor = MINX(relativeViewY) > MINX(panView) ? -1 : 1;
            NSInteger yFactor = MINY(relativeViewX) > MINY(panView) ? -1 : 1;
            
            CGFloat appendSpace = 2*(minSpace+self.cornerMargin);
            
            CGFloat offsetX = (curPoint.x - _lastCornnerPoint.x - _lastCornnerOffset.x)*xFactor + tmpWidth;
            offsetX = MAX(tmpWidth*2 + minSpace, offsetX);
            offsetX = MIN(self.frame.size.width + appendSpace, offsetX);
            
            CGFloat offsetY = (curPoint.y - _lastCornnerPoint.y - _lastCornnerOffset.y)*yFactor + tmpHeight;
            offsetY = MAX(tmpHeight*2 + minSpace, offsetY);
            offsetY = MIN(self.frame.size.height + appendSpace, offsetY);
            //NSLog(@"x = %f y = %f", offsetX, offsetY);
            if(_cropAspectRatio > 0) {
                //基于x轴计算
                CGFloat tmpY = MAX(offsetX / _cropAspectRatio, minSpace + tmpHeight * 2);
                CGFloat tmpYX = tmpY * _cropAspectRatio;
                
                //基于y轴计算
                CGFloat tmpX = MAX(offsetY * _cropAspectRatio, minSpace + tmpWidth * 2);
                CGFloat tmpXY = tmpX / _cropAspectRatio;
                
                //取变化较大的
                if((tmpYX > tmpX)) {
                    offsetX = tmpX;
                    offsetY = tmpXY;
                }else {
                    offsetY = tmpY;
                    offsetX = tmpYX;
                }
            }
            
            CGPoint toPoint = panView.center;
            toPoint.x = (offsetX - tmpWidth) * xFactor + _lastCornnerPoint.x;
            toPoint.y = (offsetY - tmpHeight) * yFactor + _lastCornnerPoint.y;
            
            toPoint.x = MIN(MAX(panView.frame.size.width/2, toPoint.x), self.frame.size.width-panView.frame.size.width/2);
            toPoint.y = MIN(MAX(panView.frame.size.height/2, toPoint.y), self.frame.size.height-panView.frame.size.height/2);
            
            panView.center = toPoint;
            
            relativeViewX.x = panView.frame.origin.x;
            relativeViewY.y = panView.frame.origin.y;
            //relativeViewX.frame = CGRectMake(MINX(panView), MINY(relativeViewX), WIDTH(relativeViewX), HEIGHT(relativeViewX));
            //relativeViewY.frame = CGRectMake(MINX(relativeViewY), MINY(panView), WIDTH(relativeViewY), HEIGHT(relativeViewY));
            
            [self resetCropAreaOnCornersFrameChanged];
            [self resetCropTransparentArea];
            [self autoAdjustImageView:NO];
        }
            break;
        case UIGestureRecognizerStateEnded:{
            [self autoAdjustViews];
            self.showCrossLines = NO;
//            custom_dispatch_after(.3, ^{
//                self.showCrossLines = NO;
//            });
        }
            break;
            
        default:
            break;
    }
}

//吸附参考线
- (CGFloat)getChangeOffsetWithOffset:(CGFloat)offset{
    return offset;
    CGFloat width = self.frame.size.width;
    CGFloat tmpOffset = offset;
    
    CGFloat tmpSpace = [UIScreen.mainScreen bounds].size.width/6.0;
    
    CGFloat tmpSpace3 = tmpSpace/3.0;
    if (tmpOffset < tmpSpace3) {
        return 0;
    }else if (tmpOffset > width-tmpSpace3){
        return width;
    }
    
    CGFloat tmpSpace1 = AutoAnchorOffsetSpace-(offset == 0 ? 0 : 4);
    CGFloat tmpSpace2 = tmpSpace-tmpSpace1;
    
    while (tmpOffset>tmpSpace) {
        tmpOffset -= tmpSpace;
    }
    
    if (tmpOffset>0 && tmpOffset<tmpSpace1) {
        tmpOffset = -tmpOffset;
    }else if (tmpOffset>tmpSpace2){
        tmpOffset = tmpSpace - tmpOffset;
    }else {
        tmpOffset = 0;
    }
    
    CGFloat returnOffset = offset + tmpOffset;
    return returnOffset;
}

#pragma mark - Position/Resize Corners&CropArea
- (void)resetCornersOnCropAreaFrameChanged {
    if (!_showCorners) {
        return;
    }
    //放大触摸范围
    CGFloat offsetX = 1.5;
    CGFloat offsetY = 1.5;
//    if (ZoomTouchRange) {
//        offsetX += MID_LINE_INTERACT_WIDTH/2;
//        offsetY += MID_LINE_INTERACT_HEIGHT/2;
//    }
    _topLeftCorner.top = _cropAreaView.top - offsetY;
    _topLeftCorner.left = _cropAreaView.left - offsetX;
    
    _topRightCorner.top = _cropAreaView.top - offsetY;
    _topRightCorner.right = _cropAreaView.right + offsetX;
    
    
    _bottomLeftCorner.bottom = _cropAreaView.bottom + offsetY;
    _bottomLeftCorner.left = _cropAreaView.left - offsetX;
    
    
    _bottomRightCorner.bottom = _cropAreaView.bottom + offsetY;
    _bottomRightCorner.right = _cropAreaView.right + offsetX;
    
}

- (void)resetCropAreaOnCornersFrameChanged {
    
    CGFloat offsetX = 0;
    CGFloat offsetY = 0;
//    if (ZoomTouchRange) {
//        offsetX = MID_LINE_INTERACT_WIDTH/2;
//        offsetY = MID_LINE_INTERACT_HEIGHT/2;
//    }
    _cropAreaView.frame = CGRectMake(MINX(_topLeftCorner) + offsetX + self.cornerMargin, MINY(_topLeftCorner) + offsetY + self.cornerMargin, MAXX(_topRightCorner) - MINX(_topLeftCorner) - self.cornerMargin * 2 - offsetX*2, MAXY(_bottomLeftCorner) - MINY(_topLeftCorner) - self.cornerMargin * 2 - offsetY*2);
}
- (void)resetCropTransparentArea {
    
    CGRect cropRect = _cropAreaView.frame;
    if (cropRect.size.height == 0 || cropRect.size.width == 0) {
        return;
    }
    //cropRect = CGRectInset(cropRect, .2, .2);
    CGFloat radius = cropRect.size.width/2;
    
    CAShapeLayer *shapeLayer = (CAShapeLayer *)_cropMaskView.layer.mask;
    
    UIBezierPath *path = [UIBezierPath bezierPathWithRect: self.bounds];
    UIBezierPath *cropPath = nil;
    if (_cycleMaskEnable) {
        cropPath = [UIBezierPath bezierPathWithRoundedRect:cropRect cornerRadius:_cropAreaView.width/2];
    }else {
        cropPath = [UIBezierPath bezierPathWithRect:cropRect];
    }

    UIBezierPath *clearPath = [cropPath bezierPathByReversingPath];
    [path appendPath: clearPath];
    if(!shapeLayer) {
        shapeLayer = [CAShapeLayer layer];
        [_cropMaskView.layer setMask: shapeLayer];
    }
    shapeLayer.path = path.CGPath;

    
    if (_showCycleLine) {//cycleLine
        CGFloat moveOffset = CGRectGetMidX(cropRect)+radius/sqrtf(2);
        _scaleView.origin = CGPointMake(moveOffset, moveOffset);
        /*
        CGRect cropRect = _cropAreaView.frame;
        CGFloat tmp = cropRect.size.width+_cycleLine.lineWidth/2 - self.width;
        if (tmp>0) {
            cropRect = CGRectInset(cropRect, tmp, tmp);
        }
        CGFloat moveOffset = CGRectGetMidX(cropRect)+radius/sqrtf(2);
        CGFloat offset = moveOffset + 8;
        
        [CATransaction begin];
        [CATransaction setDisableActions:YES];
        _scaleIcon.frame = CGRectMake(offset, offset, 24, 24);
        [CATransaction commit];
        
        offset += 5;
        CGMutablePathRef  path =  CGPathCreateMutable();
        CGPathMoveToPoint(path, nil, moveOffset, moveOffset);
        CGPathAddLineToPoint(path, nil, offset, offset);
        CGPathAddEllipseInRect(path, nil, cropRect);
        //CGPathCloseSubpath(path);
        _cycleLine.path = path;
        CGPathRelease(path);
        //*/
    }
}

- (void)animationCropTransparentAreaFromRect:(CGRect)fromRect toRect:(CGRect)toRect{
    if (CGRectEqualToRect(fromRect, toRect)) {
        return;
    }
    [_cropAreaView animationCrossLineTransparentFromRect:fromRect toRect:toRect];
    CAShapeLayer *shapeLayer = (CAShapeLayer *)_cropMaskView.layer.mask;
    if(!shapeLayer) {
        shapeLayer = [CAShapeLayer layer];
        [_cropMaskView.layer setMask: shapeLayer];
    }
    
    CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"path"];
    anim.duration = 0.3;
    
    UIBezierPath *path = [UIBezierPath bezierPathWithRect: self.bounds];
    UIBezierPath *clearPath = [[UIBezierPath bezierPathWithRect: fromRect] bezierPathByReversingPath];
    [path appendPath: clearPath];
    anim.fromValue = (__bridge id _Nullable)(path.CGPath);
    
    path = [UIBezierPath bezierPathWithRect: self.bounds];
    clearPath = [[UIBezierPath bezierPathWithRect: toRect] bezierPathByReversingPath];
    [path appendPath: clearPath];
    anim.toValue = (__bridge id _Nullable)(path.CGPath);
    shapeLayer.path = path.CGPath;
    anim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    [shapeLayer addAnimation:anim forKey:nil];
}

- (void)resetCornersOnSizeChanged {
    CGFloat tmpWidth = _cropAreaCornerWidth ;
    CGFloat tmpHeight = _cropAreaCornerHeight ;
//    if (ZoomTouchRange) {
//        tmpWidth += MID_LINE_INTERACT_WIDTH/2;
//        tmpHeight += MID_LINE_INTERACT_HEIGHT/2;
//    }
    [_topLeftCorner updateSizeWithWidth: tmpWidth height: tmpHeight];
    [_topRightCorner updateSizeWithWidth: tmpWidth height: tmpHeight];
    [_bottomLeftCorner updateSizeWithWidth: tmpWidth height: tmpHeight];
    [_bottomRightCorner updateSizeWithWidth: tmpWidth height: tmpHeight];
    
}
- (void)createCorners {
    CGFloat tmpWidth = _cropAreaCornerWidth ;
    CGFloat tmpHeight = _cropAreaCornerHeight ;
//    if (ZoomTouchRange) {
//        tmpWidth += MID_LINE_INTERACT_WIDTH/2;
//        tmpHeight += MID_LINE_INTERACT_HEIGHT/2;
//    }
    
    _topLeftCorner = [[CornerView alloc]initWithFrame: CGRectMake(0, 0, tmpWidth, tmpHeight) lineColor:_cropAreaCornerLineColor lineWidth: _cropAreaCornerLineWidth];
    _topLeftCorner.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleRightMargin;
    _topLeftCorner.cornerPosition = TKCropAreaCornerPositionTopLeft;

    _topRightCorner = [[CornerView alloc]initWithFrame: CGRectMake(WIDTH(_imageView) -  tmpWidth, 0, tmpWidth, tmpHeight) lineColor: _cropAreaCornerLineColor lineWidth: _cropAreaCornerLineWidth];
    _topRightCorner.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleLeftMargin;
    _topRightCorner.cornerPosition = TKCropAreaCornerPositionTopRight;
    
    _bottomLeftCorner = [[CornerView alloc]initWithFrame: CGRectMake(0, HEIGHT(_imageView) -  tmpHeight, tmpWidth, tmpHeight) lineColor: _cropAreaCornerLineColor lineWidth: _cropAreaCornerLineWidth];
    _bottomLeftCorner.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleRightMargin;
    _bottomLeftCorner.cornerPosition = TKCropAreaCornerPositionBottomLeft;
    
    _bottomRightCorner = [[CornerView alloc]initWithFrame: CGRectMake(WIDTH(_imageView) - tmpWidth, HEIGHT(_imageView) -  tmpHeight, tmpWidth, tmpHeight) lineColor: _cropAreaCornerLineColor lineWidth: _cropAreaCornerLineWidth];
    _bottomRightCorner.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin;
    _bottomRightCorner.cornerPosition = TKCropAreaCornerPositionBottomRight;
    
    _topLeftCorner.relativeViewX = _bottomLeftCorner;
    _topLeftCorner.relativeViewY = _topRightCorner;
    
    _topRightCorner.relativeViewX = _bottomRightCorner;
    _topRightCorner.relativeViewY = _topLeftCorner;
    
    _bottomLeftCorner.relativeViewX = _topLeftCorner;
    _bottomLeftCorner.relativeViewY = _bottomRightCorner;
    
    _bottomRightCorner.relativeViewX = _topRightCorner;
    _bottomRightCorner.relativeViewY = _bottomLeftCorner;
    
    [self addSubview: _topLeftCorner];
    [self addSubview: _topRightCorner];
    [self addSubview: _bottomLeftCorner];
    [self addSubview: _bottomRightCorner];
    [self bindPanGestures];
}

- (void)removeCorners{
    [_topLeftCorner removeFromSuperview];
    [_topRightCorner removeFromSuperview];
    [_bottomLeftCorner removeFromSuperview];
    [_bottomRightCorner removeFromSuperview];
    _topLeftCorner = nil;
    _topRightCorner = nil;
    _bottomLeftCorner = nil;
    _bottomRightCorner = nil;
    
    [_panGestures removeObject:_topLeftPan];
    [_panGestures removeObject:_topRightPan];
    [_panGestures removeObject:_bottomLeftPan];
    [_panGestures removeObject:_bottomRightPan];
}

- (void)createMidLines {
    
    if(_topMidLine && _bottomMidLine && _leftMidLine && _rightMidLine){
        _topMidLine.hidden = NO;
        _bottomMidLine.hidden = NO;
        _leftMidLine.hidden = NO;
        _rightMidLine.hidden = NO;
        return;
    }
    _topMidLine = [[MidLineView alloc]initWithLineWidth: _cropAreaMidLineWidth lineHeight: _cropAreaMidLineHeight lineColor: _cropAreaMidLineColor];
    _topMidLine.type = TKMidLineTypeTop;
    
    _bottomMidLine = [[MidLineView alloc]initWithLineWidth: _cropAreaMidLineWidth lineHeight: _cropAreaMidLineHeight lineColor: _cropAreaMidLineColor];
    _bottomMidLine.type = TKMidLineTypeBottom;
    
    _leftMidLine = [[MidLineView alloc]initWithLineWidth: _cropAreaMidLineWidth lineHeight: _cropAreaMidLineHeight lineColor: _cropAreaMidLineColor];
    _leftMidLine.type = TKMidLineTypeLeft;
    
    _rightMidLine = [[MidLineView alloc]initWithLineWidth: _cropAreaMidLineWidth lineHeight: _cropAreaMidLineHeight lineColor: _cropAreaMidLineColor];
    _rightMidLine.type = TKMidLineTypeRight;
    
    _topMidPan = [[UIPanGestureRecognizer alloc]initWithTarget:self action: @selector(handleMidPan:)];
    [_topMidLine addGestureRecognizer: _topMidPan];
    
    _bottomMidPan = [[UIPanGestureRecognizer alloc]initWithTarget:self action: @selector(handleMidPan:)];
    [_bottomMidLine addGestureRecognizer: _bottomMidPan];

    _leftMidPan = [[UIPanGestureRecognizer alloc]initWithTarget:self action: @selector(handleMidPan:)];
    [_leftMidLine addGestureRecognizer: _leftMidPan];

    _rightMidPan = [[UIPanGestureRecognizer alloc]initWithTarget:self action: @selector(handleMidPan:)];
    [_rightMidLine addGestureRecognizer: _rightMidPan];

    [self addSubview: _topMidLine];
    [self addSubview: _bottomMidLine];
    [self addSubview: _leftMidLine];
    [self addSubview: _rightMidLine];
    //[self insertSubview:_topMidLine aboveSubview:self.imageView];
    //[self insertSubview:_bottomMidLine aboveSubview:self.imageView];
    //[self insertSubview:_leftMidLine aboveSubview:self.imageView];
    //[self insertSubview:_rightMidLine aboveSubview:self.imageView];
    [_panGestures addObject:_topMidPan];
    [_panGestures addObject:_bottomMidPan];
    [_panGestures addObject:_leftMidPan];
    [_panGestures addObject:_rightMidPan];
}
- (void)removeMidLines {
    if(_topMidLine && _bottomMidLine && _leftMidLine && _rightMidLine){
        _topMidLine.hidden = YES;
        _bottomMidLine.hidden = YES;
        _leftMidLine.hidden = YES;
        _rightMidLine.hidden = YES;
        return;
    }
    if(!_topMidLine && !_bottomMidLine && !_leftMidLine && !_rightMidLine) return;
    [_topMidLine removeFromSuperview];
    [_bottomMidLine removeFromSuperview];
    [_leftMidLine removeFromSuperview];
    [_rightMidLine removeFromSuperview];
    
    _topMidLine = nil;
    _bottomMidLine = nil;
    _leftMidLine = nil;
    _rightMidLine = nil;
    
    [_panGestures removeObject:_topMidPan];
    [_panGestures removeObject:_bottomMidPan];
    [_panGestures removeObject:_leftMidPan];
    [_panGestures removeObject:_rightMidPan];
}
- (void)resetMidLines {
    //撑满_cropAreaView边界
    CGFloat offset = 0;
    
    CGRect rect = _topMidLine.frame;
    rect.size.width = _cropAreaView.width;
    rect.origin.x = _cropAreaView.centerX - rect.size.width/2;
    rect.origin.y = _cropAreaView.top-offset - rect.size.height/2;
    _topMidLine.frame = rect;
    
    rect = _bottomMidLine.frame;
    rect.size.width = _cropAreaView.width;
    rect.origin.x = _cropAreaView.centerX - rect.size.width/2;
    rect.origin.y = _cropAreaView.bottom+offset - rect.size.height/2;
    _bottomMidLine.frame = rect;

    rect = _leftMidLine.frame;
    rect.size.height = _cropAreaView.height;
    rect.origin.x = _cropAreaView.left-offset - rect.size.width/2;
    rect.origin.y = _cropAreaView.centerY - rect.size.height/2;
    _leftMidLine.frame = rect;
    
    rect = _rightMidLine.frame;
    rect.size.height = _cropAreaView.height;
    rect.origin.x = _cropAreaView.right+offset - rect.size.width/2;
    rect.origin.y = _cropAreaView.centerY - rect.size.height/2;
    _rightMidLine.frame = rect;
    
}
- (void)resetImageView {
    //
    CGFloat selfAspectRatio = WIDTH(_cropAreaView) / HEIGHT(_cropAreaView);
    if(_imageAspectRatio > selfAspectRatio) {
        _paddingLeftRight = 0;
        _paddingTopBottom = floor((HEIGHT(_cropAreaView) - WIDTH(_cropAreaView) / _imageAspectRatio) / 2.0);
        _imageView.frame = CGRectMake(0, _paddingTopBottom, WIDTH(_cropAreaView), floor(WIDTH(_cropAreaView) / _imageAspectRatio));
    }
    else {
        _paddingTopBottom = 0;
        _paddingLeftRight = floor((WIDTH(_cropAreaView) - HEIGHT(_cropAreaView) * _imageAspectRatio) / 2.0);
        _imageView.frame = CGRectMake(_paddingLeftRight, 0, floor(HEIGHT(_cropAreaView) * _imageAspectRatio), HEIGHT(_cropAreaView));
    }
    _cropMaskView.frame = self.bounds;
}
- (void)resetCropAreaByAspectRatio {
    
    if(_imageAspectRatio == 0) return;
    CGRect toRect = self.cropAreaViewWillFrame;
    //self.showCrossLines = NO;
    //_ignoreCrossLine = YES;
    [self animationCropTransparentAreaFromRect:_cropAreaView.frame toRect:toRect];
    
    [UIView animateWithDuration:.3 animations:^{
        CGAffineTransform transform = CGAffineTransformMakeScale(1, 1);
        transform = CGAffineTransformRotate(transform, 0);
        _imageView.zoomScrollView.transform = transform;
        _cropAreaView.frame = toRect;
        //_imageView.frame = toRect;
        [self resetCornersOnCropAreaFrameChanged];
        [_imageView updateCropRect:toRect reset:YES change:nil];
    } completion:^(BOOL finished) {
        //_ignoreCrossLine = NO;
        //self.showCrossLines = YES;
    }];
}

- (CGRect)cropAreaViewWillFrame{
    if(_imageAspectRatio == 0) return CGRectZero;
    CGFloat tmpCornerMargin = self.tmpCornerMargin;
    CGFloat width, height;
    CGFloat maxWidth = WIDTH(self) - 2 * tmpCornerMargin;
    CGFloat maxHeight = HEIGHT(self) - 2 * tmpCornerMargin;
    if(_cropAspectRatio == 0) {
        
        if(_imageAspectRatio > _currCropAspectRatio) {
            height = maxHeight;
            width = height * _currCropAspectRatio;
            if (width>maxWidth) {
                CGFloat tmpScale = maxWidth/width;
                width = maxWidth;
                height *= tmpScale;
            }
        }else {
            width = WIDTH(self) - 2 * tmpCornerMargin;
            height = width / _currCropAspectRatio;
            if (height>maxHeight) {
                CGFloat tmpScale = maxHeight/height;
                height = maxHeight;
                width *= tmpScale;
            }
        }
        
        if(_showMidLines) {
            [self createMidLines];
            [self resetMidLines];
        }
    }else {
        //[self removeMidLines];
        
        height = HEIGHT(self) - 2 * tmpCornerMargin;
        width = height * _cropAspectRatio;
        CGFloat tmpW = WIDTH(self) - 2 * tmpCornerMargin;
        
        if(tmpW < width) {
            width = tmpW;
            height = width / _cropAspectRatio;
        }
    }
    CGRect rect = CGRectMake((WIDTH(self) - width) / 2.0, (HEIGHT(self) - height) / 2.0, width, height);
    return rect;
}

- (void)resetCropAreaByScaleFactor: (CGFloat)scaleFactor {
    
    CGPoint center = _cropAreaView.center;
    CGFloat tmpCornerMargin = self.tmpCornerMargin;
    CGFloat width = _pinchOriSize.width * scaleFactor;
    CGFloat height = _pinchOriSize.height * scaleFactor;
    CGFloat widthMax = MIN(WIDTH(_imageView) - center.x - tmpCornerMargin, center.x - tmpCornerMargin) * 2;
    CGFloat widthMin = _minSpace + _cropAreaCornerWidth * 2.0 - tmpCornerMargin * 2.0;
    CGFloat heightMax = MIN(HEIGHT(_imageView) - center.y - tmpCornerMargin, center.y - tmpCornerMargin) * 2;
    CGFloat heightMin = _minSpace + _cropAreaCornerWidth * 2.0 - tmpCornerMargin * 2;
    
    BOOL isMinimum = NO;
    if(_cropAspectRatio > 1) {
        if(height <= heightMin) {
            height = heightMin;
            width = height * _cropAspectRatio;
            isMinimum = YES;
        }
    }
    else {
        if(width <= widthMin) {
            width = widthMin;
            height = width / (_cropAspectRatio == 0 ? 1 : _cropAspectRatio);
            isMinimum = YES;
        }
    }
    if(!isMinimum) {
        if(_cropAspectRatio == 0) {
            if(width >= widthMax) {
                width = MIN(width, WIDTH(_imageView) - 2 * tmpCornerMargin);
                center.x = center.x > WIDTH(_imageView) / 2.0 ? WIDTH(_imageView) - width / 2.0 - tmpCornerMargin : width / 2.0 + tmpCornerMargin;
            }
            if(height > heightMax) {
                height = MIN(height, HEIGHT(_imageView) - 2 * tmpCornerMargin);
                center.y = center.y > HEIGHT(_imageView) / 2.0 ? HEIGHT(_imageView) - height / 2.0 - tmpCornerMargin : height / 2.0 + tmpCornerMargin;
            }
            
        }
        else if(_imageAspectRatio > _cropAspectRatio) {
            if(height >= heightMax) {
                height = MIN(height, HEIGHT(_imageView) - 2 * tmpCornerMargin);
                center.y = center.y > HEIGHT(_imageView) / 2.0 ? HEIGHT(_imageView) - height / 2.0 - tmpCornerMargin : height / 2.0 + tmpCornerMargin;
            }
            width = height * _cropAspectRatio;
            if(width > widthMax) {
                center.x = center.x > WIDTH(_imageView) / 2.0 ? WIDTH(_imageView) - width / 2.0 - tmpCornerMargin : width / 2.0 + tmpCornerMargin;
            }
        }
        else {
            if(width >= widthMax) {
                width = MIN(width, WIDTH(_imageView) - 2 * tmpCornerMargin);
                center.x = center.x > WIDTH(_imageView) / 2.0 ? WIDTH(_imageView) - width / 2.0 - tmpCornerMargin : width / 2.0 + tmpCornerMargin;
            }
            height = width / _cropAspectRatio;
            if(height > heightMax) {
                center.y = center.y > HEIGHT(_imageView) / 2.0 ? HEIGHT(_imageView) - height / 2.0 - tmpCornerMargin : height / 2.0 + tmpCornerMargin;
            }
        }
    }
    _cropAreaView.bounds = CGRectMake(0, 0, width, height);
    _cropAreaView.center = center;
    [self resetCornersOnCropAreaFrameChanged];
    
}
#pragma mark - 初始化方形
- (void)initSqureSettingWithImage:(UIImage *)image{
    self.clipsToBounds = YES;
    self.crossLinesEnable = YES;
    self.needScaleCrop = NO;
    //_cropView.showCrossLines = YES;
    self.cropAreaCornerWidth = 13;
    self.cropAreaCornerHeight = 13;
    self.minSpace = self.width/3.0;
    self.showCorners = NO;
    //self.cropAreaCornerLineColor = [UIColor colorWithHex:0x5bc7ff];
    //self.cropAreaBorderLineColor = COLOR_CUSTOM_BLUE;
    self.cropAreaBorderLineWidth = 1;
    
    //self.cropAreaCornerLineColor = [UIColor clearColor];
    //self.cropAreaCornerLineWidth = 0;
    
    self.cropAreaMidLineWidth = 60;
    self.cropAreaMidLineHeight = 6;
    //self.cropAreaMidLineColor = COLOR_CUSTOM_BLUE;
    
    self.maskColor = [UIColor whiteColor];
    
    [self showCropView:NO];
    
    _toCropImage = image;
    _imageView.image = image;
    
    [self updateSqureWithRatio:_firstOpenType==0 ? -1 : 0  animation:NO];
}

- (void)showCropView:(BOOL)show{
    self.showMidLines = show;
    if (show) {
        //[self createMidLines];
        [self setOtherPanGestureEnable:YES gesture:nil];
    }else {
        //[self removeMidLines];
        [self setOtherPanGestureEnable:NO gesture:nil];
    }
}
- (void)updateSqureWithRatio:(CGFloat)ratio{
    [self updateSqureWithRatio:ratio animation:YES];
}
- (void)updateSqureWithRatio:(CGFloat)ratio animation:(BOOL)animation{
    //横图(同方图)  展示上1/2  //竖图展示左2/3;
    CGSize imageSize = _imageView.zoomImageView.size;
    CGRect cropFrame = _cropAreaView.frame;
    CGFloat leftOffset = 0;
    CGFloat topOffset = 0;

    if (ratio == 0) {//撑满
        //leftOffset = topOffset = 0;
        cropFrame = CGRectMake(leftOffset, topOffset, self.width-leftOffset*2, self.height-topOffset*2);
    }else if (ratio == -1) {//默认 根据尺寸布局
        [_imageView resetRotation];
        imageSize = _toCropImage.size;
        if (imageSize.width == imageSize.height) {//正方形 居中
            leftOffset = self.width/6;
            topOffset = leftOffset;
            cropFrame = CGRectMake(leftOffset, topOffset, self.width-leftOffset*2, self.height-topOffset*2);
        }else {//
            if (imageSize.width>imageSize.height) {//宽的 居下
                cropFrame = CGRectMake(0, self.height/3, self.width, self.height*2.0/3.0);
            }else{//长的居左
                cropFrame = CGRectMake(0, 0, self.width*2.0/3.0, self.height);
            }
        }
    }else {//其他比例
        if (ratio == 1) {
            leftOffset = self.width/6;
            topOffset = leftOffset;
        }else {
            if (ratio > 1) {
                leftOffset = 0;
                topOffset = (self.width - self.width/ratio)/2;
            }else {
                topOffset = 0;
                leftOffset = (self.width - self.width*ratio)/2;
            }
        }
        cropFrame = CGRectMake(leftOffset, topOffset, self.width-leftOffset*2, self.height-topOffset*2);
    }
    
    CGFloat scaleX = imageSize.width/cropFrame.size.width;
    CGFloat scaleY = imageSize.height/cropFrame.size.height;
    CGFloat scale = MIN(scaleX, scaleY);//缩小倍数
    CGFloat currScale = _imageView.zoomScrollView.zoomScale;
    currScale /= scale;
    
    if (animation) {
        [self animationCropTransparentAreaFromRect:_cropAreaView.frame toRect:cropFrame];
        [UIView animateWithDuration:.3 animations:^{
            _cropAreaView.frame = cropFrame;
            [self resetCropTransparentArea];
            [self autoAdjustViews];
            _imageView.zoomScrollView.zoomScale = currScale;
            [_imageView moveImageToCenterWithAnimation:NO];
        }];
    }else {
        _cropAreaView.frame = cropFrame;
        [self resetCropTransparentArea];
        [self autoAdjustViews];
        _imageView.zoomScrollView.zoomScale = currScale;
        [_imageView moveImageToCenterWithAnimation:NO];
    }
}

#pragma mark - Setter & Getters
- (void)setScaleFactor:(CGFloat)scaleFactor {
    
    _pinchOriSize = _cropAreaView.frame.size;
    [self resetCropAreaByScaleFactor: scaleFactor];
    
}
- (CGFloat)cornerMargin {
    
    return _cropAreaCornerLineWidth - _cropAreaBorderLineWidth;
    
}
- (void)setMaskColor:(UIColor *)maskColor {
    _maskColor = maskColor;
    if (_maskImage) {
        return;
    }
    _cropMaskView.backgroundColor = maskColor;
    if (_cycleMaskEnable) {
        _cropAreaView.borderColor = maskColor;
    }
}

- (void)setMaskImage:(UIImage *)maskImage{
    _maskImage = maskImage;
    if (_maskImage) {
        CGFloat scale = _maskImage.size.width/self.width;
        UIImage *image = _maskImage;
        if (scale > 1) {
            CGSize size = image.size;
            size.width /= scale;
            size.height /= scale;
            UIGraphicsBeginImageContextWithOptions(size, NO, scale);
            [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
            image = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
        }
        _cropMaskView.backgroundColor = [UIColor colorWithPatternImage:image];
    }else {
        self.maskColor = _maskColor;
    }
}

- (void)setToCropImage:(UIImage *)toCropImage {
    
    _toCropImage = toCropImage;
    _imageAspectRatio = toCropImage.size.width / toCropImage.size.height;
    _imageView.image = toCropImage;
    _currCropAspectRatio = _imageAspectRatio;
    [self resetCropAreaByAspectRatio];
    
}

- (void)onlyChangeImage:(UIImage *)image{
    _toCropImage = image;
    [_imageView onlyChangeImage:image];
}

- (void)setNewCropImage:(UIImage *)image{
    _toCropImage = image;
    _imageView.image = image;
    _imageAspectRatio = image.size.width / image.size.height;
}


- (void)setNeedScaleCrop:(BOOL)needScaleCrop {
    
    if(!_needScaleCrop && needScaleCrop) {
        _cropAreaPinch = [[UIPinchGestureRecognizer alloc]initWithTarget: self action:@selector(handleImagePinch:)];
        [_cropAreaView addGestureRecognizer: _cropAreaPinch];
    }
    else if(_needScaleCrop && !needScaleCrop){
        [_cropAreaView removeGestureRecognizer: _cropAreaPinch];
        _cropAreaPinch = nil;
    }
    _needScaleCrop = needScaleCrop;
    
}
- (void)setCropAreaCrossLineWidth:(CGFloat)cropAreaCrossLineWidth {
    
    _cropAreaCrossLineWidth = cropAreaCrossLineWidth;
    _cropAreaView.crossLineWidth = cropAreaCrossLineWidth;
    
}
- (void)setCropAreaCrossLineColor:(UIColor *)cropAreaCrossLineColor {
    
    _cropAreaCrossLineColor = cropAreaCrossLineColor;
    _cropAreaView.crossLineColor = cropAreaCrossLineColor;
    
}
- (void)setCropAreaMidLineWidth:(CGFloat)cropAreaMidLineWidth {
    
    _cropAreaMidLineWidth = cropAreaMidLineWidth;
    _topMidLine.lineWidth = cropAreaMidLineWidth;
    _bottomMidLine.lineWidth = cropAreaMidLineWidth;
    _leftMidLine.lineWidth = cropAreaMidLineWidth;
    _rightMidLine.lineWidth = cropAreaMidLineWidth;
    if(_showMidLines) {
        [self resetMidLines];
    }
    
}
- (void)setCropAreaMidLineHeight:(CGFloat)cropAreaMidLineHeight {

    _cropAreaMidLineHeight = cropAreaMidLineHeight;
    _topMidLine.lineHeight = cropAreaMidLineHeight;
    _bottomMidLine.lineHeight = cropAreaMidLineHeight;
    _leftMidLine.lineHeight = cropAreaMidLineHeight;
    _rightMidLine.lineHeight = cropAreaMidLineHeight;
    if(_showMidLines) {
        [self resetMidLines];
    }
    
}
- (void)setCropAreaMidLineColor:(UIColor *)cropAreaMidLineColor {
    
    _cropAreaMidLineColor = cropAreaMidLineColor;
    _topMidLine.lineColor = cropAreaMidLineColor;
    _bottomMidLine.lineColor = cropAreaMidLineColor;
    _leftMidLine.lineColor = cropAreaMidLineColor;
    _rightMidLine.lineColor = cropAreaMidLineColor;
    
}
- (void)setCropAreaBorderLineWidth:(CGFloat)cropAreaBorderLineWidth {
    
    _cropAreaBorderLineWidth = cropAreaBorderLineWidth;
    _cropAreaView.borderWidth = cropAreaBorderLineWidth;
    [self resetCropAreaOnCornersFrameChanged];
    
}
- (void)setCropAreaBorderLineColor:(UIColor *)cropAreaBorderLineColor {
    
    _cropAreaBorderLineColor = cropAreaBorderLineColor;
    _cropAreaView.borderColor = cropAreaBorderLineColor;
    
}
- (void)setCropAreaCornerLineColor:(UIColor *)cropAreaCornerLineColor {
    
    _cropAreaCornerLineColor = cropAreaCornerLineColor;
    _topLeftCorner.lineColor = cropAreaCornerLineColor;
    _topRightCorner.lineColor = cropAreaCornerLineColor;
    _bottomLeftCorner.lineColor = cropAreaCornerLineColor;
    _bottomRightCorner.lineColor = cropAreaCornerLineColor;
    
}
- (void)setCropAreaCornerLineWidth:(CGFloat)cropAreaCornerLineWidth {
    
    _cropAreaCornerLineWidth = cropAreaCornerLineWidth;
    _topLeftCorner.lineWidth = cropAreaCornerLineWidth;
    _topRightCorner.lineWidth = cropAreaCornerLineWidth;
    _bottomLeftCorner.lineWidth = cropAreaCornerLineWidth;
    _bottomRightCorner.lineWidth = cropAreaCornerLineWidth;
    [self resetCropAreaByAspectRatio];
    
}
- (void)setCropAreaCornerWidth:(CGFloat)cropAreaCornerWidth {
    
    _cropAreaCornerWidth = cropAreaCornerWidth;
    [self resetCornersOnSizeChanged];

}
- (void)setCropAreaCornerHeight:(CGFloat)cropAreaCornerHeight {
    
    _cropAreaCornerHeight = cropAreaCornerHeight;
    [self resetCornersOnSizeChanged];
    
}
- (void)setCropAspectRatio:(CGFloat)cropAspectRatio {
    
    _cropAspectRatio = MAX(cropAspectRatio, 0);
    if (_cropAspectRatio == 0) {
        _currCropAspectRatio = _imageAspectRatio;
    }
    self.toCropImage = _toCropImage;
//    [self resetCropAreaByAspectRatio];

}
- (void)setShowMidLines:(BOOL)showMidLines {
    
    
    if(!_showMidLines && showMidLines) {
        [self createMidLines];
        [self resetMidLines];
    }
    else if(_showMidLines && !showMidLines) {
        [self removeMidLines];
    }
    
    _showMidLines = showMidLines;
    
}

- (void)setCornerBorderInImage:(BOOL)cornerBorderInImage {

    _cornerBorderInImage = cornerBorderInImage;
    [self resetCropAreaByAspectRatio];
    
}
- (void)setFrame:(CGRect)frame {
    
    [super setFrame: frame];
    _cropMaskView.frame = self.bounds;
    
}


- (void)setShowCorners:(BOOL)showCorners{
    if (_showCorners == showCorners) {
        return;
    }
    _showCorners = showCorners;
    
    if (_showCorners) {
        [self createCorners];
    }else {
        [self removeCorners];
    }
}

#pragma mark - tmpImageView 滤镜处理过度

- (UIImageView *)tmpImageView{
    if (_tmpImageView) {
        return _tmpImageView;
    }
    self.tmpImageView = [[UIImageView alloc] initWithFrame:_imageView.frame];
    _tmpImageView.hidden = YES;
    _tmpImageView.userInteractionEnabled = NO;
    return _tmpImageView;
}

- (void)setTmpImageViewHidden:(BOOL)hidden{
    if (hidden) {
        _tmpImageView.hidden = YES;
        return;
    }
    
    [self insertSubview:self.tmpImageView aboveSubview:_imageView];
    
    _tmpImageView.frame = [_imageView.zoomScrollView convertRect:_imageView.zoomImageView.frame toView:_imageView];
    
    //UIImage *image = [_imageView snapshotImageAfterScreenUpdates:NO];
    UIImage *image = _imageView.image;
//    GPUImagePicture * inputImage = [[GPUImagePicture alloc] initWithImage:image];
//    [inputImage processImage];
//    [inputImage addTarget: _tmpImageView];
    _tmpImageView.hidden = NO;
}

#pragma mark - cycle
//初始化圆
- (void)initCycleSettingWithImage:(UIImage *)image{
    self.clipsToBounds = YES;
    //self.crossLinesEnable = YES;
    self.showMidLines = NO;
    self.cropAreaBorderLineWidth = 0;
    self.needScaleCrop = NO;
    //_cropView.showCrossLines = YES;
    //self.cropAreaCornerWidth = 13;
    //self.cropAreaCornerHeight = 13;
    self.minSpace = self.width/6.0;
    self.showCorners = NO;
    //_cycleLineColor = COLOR_CUSTOM_BLUE;
    _cycleLineWidth = 2;
    //self.cropAreaCornerLineColor = [UIColor colorWithHex:0x5bc7ff];
    //self.cropAreaBorderLineColor = [UIColor colorWithHex:0x5bc7ff];
    //self.cropAreaCornerLineColor = [UIColor clearColor];
    //self.cropAreaBorderLineColor = [UIColor clearColor];
    
    //self.cropAreaCornerLineWidth = 3;
    //self.cropAreaBorderLineWidth = 0;
    
    //self.cropAreaMidLineWidth = 60;
    //self.cropAreaMidLineHeight = 6;
    //self.cropAreaMidLineColor = [UIColor colorWithHex:0x5bc7ff];
    
    self.maskColor = UIColor.whiteColor;
    
    //[self showCropView:YES];
    
    _toCropImage = image;
    _imageView.image = image;
    
    //
    _cycleWidth = KScreenWidth-30;
    CGRect rect = CGRectMake(15, 15, _cycleWidth, _cycleWidth);
    _cropAreaView.frame = rect;
    
    [self resetCropTransparentArea];
    [self autoAdjustViews];
    //[self setImageViewFrame:rect];
    _lastCropRect = _cropAreaView.frame;
}

- (void)setCycleMaskEnable:(BOOL)cycleMaskEnable{
    if (_cycleMaskEnable == cycleMaskEnable) {
        return;
    }
    _cycleMaskEnable = cycleMaskEnable;
    [self showCropView:NO];
    
    [self resetCropTransparentArea];
}

- (void)setShowCycleLine:(BOOL)showCycleLine{
    if (_showCycleLine == showCycleLine) {
        return;
    }
    _showCycleLine = showCycleLine;
    
    if (_showCycleLine) {
        
        if (!_scaleView) {
            CGFloat offset = KScreenWidth/2 + _cycleWidth/2/sqrtf(2);
            CGFloat width  = KScreenWidth - offset-10;
            _scaleView = [[BaseView alloc] initWithFrame:CGRectMake(offset, offset, width, width)];
            [self addSubview:_scaleView];
            _scaleIcon = [CALayer layer];
            _scaleIcon.contents = (id)[UIImage imageNamed:@"scale_icon"].CGImage;
            _scaleIcon.contentsScale = [UIScreen mainScreen].scale;
            CGFloat tmp = (width-24)/2;
            _scaleIcon.frame = CGRectMake(tmp, tmp, 24, 24);
            [_scaleView.layer addSublayer:_scaleIcon];
            
            tmp += 8;
            self.cycleLine = [CAShapeLayer layer];
            _cycleLine.frame = CGRectMake(0, 0, tmp, tmp);
            
            CGMutablePathRef  path =  CGPathCreateMutable();
            CGPathMoveToPoint(path, nil, 0, 0);
            CGPathAddLineToPoint(path, nil, tmp, tmp);
            _cycleLine.path = path;
            CGPathRelease(path);
            
            _cycleLine.fillColor = [UIColor clearColor].CGColor;
            _cycleLine.strokeColor = _cycleLineColor ? _cycleLineColor.CGColor : [UIColor colorWithWhite:1 alpha:0.5].CGColor;
            _cycleLine.lineWidth = _cycleLineWidth ?: 2;
            //_cropLine.masksToBounds = YES;
            [_scaleView.layer addSublayer:_cycleLine];
        }
        _scaleView.hidden = NO;
        _panGesture.enabled = YES;
        
        if (!_panGesture) {
            self.panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(onPanGesture:)];
            [_scaleView addGestureRecognizer:_panGesture];
        }
        _panGesture.enabled = YES;
    }else {
        _scaleView.hidden = YES;
        _panGesture.enabled = NO;
    }
    [self resetCropTransparentArea];
}

- (void)setCycleLineWidth:(CGFloat)cropCycleWidth{
    if (_cycleLineWidth == cropCycleWidth) {
        return;
    }
    _cycleLineWidth = cropCycleWidth;
    if (_cycleMaskEnable) {
        _cycleLine.lineWidth = _cycleLineWidth;
        //[self resetCropTransparentArea];
    }
}
- (void)setCycleLineColor:(UIColor *)cycleLineColor{
    if (_cycleLineColor == cycleLineColor) {
        return;
    }
    _cycleLineColor = cycleLineColor;
    
    if (_cycleMaskEnable) {
        _cycleLine.strokeColor = _cycleLineColor.CGColor;
        //[self resetCropTransparentArea];
    }
}

- (void)setCycleWidth:(CGFloat)cycleWidth{
    if (_cycleWidth == cycleWidth) {
        return;
    }
    _cycleWidth = cycleWidth;
    if (_cycleMaskEnable) {
        CGFloat center = _cropAreaView.centerX;
        CGRect rect = _cropAreaView.frame;
        rect.size = CGSizeMake(cycleWidth, cycleWidth);
        rect.origin.x = center-cycleWidth/2;
        rect.origin.y = rect.origin.x;
        _cropAreaView.frame = rect;
        [self autoAdjustImageView:NO];
        //[self autoScaleImageView:NO];
        [self resetCropTransparentArea];
    }
}

- (void)onPanGesture:(UIPanGestureRecognizer *)sender{
    static NSInteger __lastFinger;
    static CGPoint __lastPoint;
    static CGFloat __lastDistance;
    static CGFloat __lastWidth;
    CGPoint curPoint = [sender locationInView:self];
    switch (sender.state) {
        case UIGestureRecognizerStateBegan:{
            __lastPoint = curPoint;
            __lastFinger = sender.numberOfTouches;
            __lastWidth = _cycleWidth;
            __lastDistance = CGPointGetDistanceToPoint(curPoint, self.center);
            self.showCrossLines = YES;
        }
            break;
        case UIGestureRecognizerStateChanged:{
            self.showCrossLines = YES;
            if (__lastFinger != sender.numberOfTouches) {
                __lastPoint = curPoint;
                __lastFinger = sender.numberOfTouches;
                __lastWidth = _cycleWidth;
                __lastDistance = CGPointGetDistanceToPoint(curPoint, self.center);
                //break;
            }
            CGFloat thisDistance = CGPointGetDistanceToPoint(curPoint, self.center);
            
            CGFloat maskWidth = __lastWidth + (thisDistance-__lastDistance)*2;
            
            self.cycleWidth = MIN(self.width, MAX(self.width/3.0, maskWidth));
            
        }
            break;
            
        default:{
            //[self updateItemLimit];
            [self autoAdjustImageView:NO];
            [self resetCropTransparentArea];
            [self autoAdjustViews];
            if (self.customAction) {
                self.customAction(@"圆", cat_done);
            }
            custom_dispatch_after(.3, ^{
                self.showCrossLines = NO;
            });
        }
            break;
    }
}

#pragma mark - KVO CallBack
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    
    if([object isEqual: _cropAreaView]) {
        if(_showMidLines){
            [self resetMidLines];
        }
        //[self resetCropTransparentArea];
    }
}
#pragma Instance Methods
- (UIImage *)currentCroppedImage {

    if ([_imageView isKindOfClass:[ITShowImageView class]]) {
        return [_imageView outputImage];
    }
    CGFloat scaleFactor = WIDTH(_imageView) / _toCropImage.size.width;
    CGRect cropRect = CGRectMake((MINX(_cropAreaView) + _cropAreaBorderLineWidth), (MINY(_cropAreaView) + _cropAreaBorderLineWidth), (WIDTH(_cropAreaView) - 2 * _cropAreaBorderLineWidth), (HEIGHT(_cropAreaView) - 2 * _cropAreaBorderLineWidth));
    
    CGRect cropImageRect = [_imageView convertRect:cropRect fromView:self];
    cropImageRect.origin.x /= scaleFactor;
    cropImageRect.origin.y /= scaleFactor;
    cropImageRect.size.width /= scaleFactor;
    cropImageRect.size.height /= scaleFactor;
    return [_toCropImage imageAtRect: cropImageRect];
}

- (UIImage *)getFullViewImage{
    UIImage *cropImage = _imageView.zoomImageView.image;
    
    CGRect imageFrame = [_imageView.zoomScrollView convertRect:_imageView.zoomImageView.frame toView:_imageView];
    
    CGFloat scale = cropImage.size.width/imageFrame.size.width;
    scale = MIN((2500.0/KScreenWidth), scale);
    scale = MAX(scale, [UIScreen mainScreen].scale);
    scale = (int)(scale+0.5);
    //防止黑/白边 画框尽量取整
    CGFloat width = (int)(KScreenWidth*scale + 0.5);
    scale = width/KScreenWidth;//反向取scale
    CGRect contentRect = CGRectMake(0, 0, width, width);
    UIGraphicsBeginImageContextWithOptions(contentRect.size, YES, cropImage.scale);
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextAddRect(context, CGRectInset(contentRect, -1, -1));
    
    
    //有透明度则 先画图片 再画遮罩
    CGRect imageRect = imageFrame;
    imageRect.origin.x *= scale;
    imageRect.origin.y *= scale;
    imageRect.size.width *= scale;
    imageRect.size.height *= scale;
    
    CGRect cropRect = _cropAreaView.frame;
    //*
    cropRect.origin.x = (cropRect.origin.x*scale);
    cropRect.origin.y = (cropRect.origin.y*scale);
    cropRect.size.width = (cropRect.size.width*scale);
    cropRect.size.height = (cropRect.size.height*scale);
    //*/
    
    if (imageRect.origin.x > cropRect.origin.x) {
        imageRect.origin.x = cropRect.origin.x;
    }
    if (imageRect.origin.y > cropRect.origin.y) {
        imageRect.origin.y = cropRect.origin.y;
    }
    
    CGFloat rotate = atan2(self.transform.b, self.transform.a);//CGAffineTransformGetRotation(_imageView.transform);
    BOOL hasRotate = rotate != 0;
    if (hasRotate) {
        CGPoint center = CGPointMake(contentRect.size.width/2, contentRect.size.height/2);
        //以中心点旋转 然后回到原点
        CGContextConcatCTM(context, CGAffineTransformMakeTranslation(center.x, center.y));
        CGContextConcatCTM(context, CGAffineTransformMakeRotation(rotate));
        CGContextConcatCTM(context, CGAffineTransformMakeTranslation(-center.x, -center.y));
        [cropImage drawInRect:imageRect];
        //旋转恢复.
        CGContextConcatCTM(context, CGAffineTransformMakeTranslation(center.x, center.y));
        CGContextConcatCTM(context, CGAffineTransformMakeRotation(-rotate));
        CGContextConcatCTM(context, CGAffineTransformMakeTranslation(-center.x, -center.y));

    }else {
        [cropImage drawInRect:imageRect];
    }
    
    CGFloat offsetx = CGRectGetMaxX(imageRect) - CGRectGetMaxX(cropRect);
    if (offsetx < 0) {
        cropRect.size.width += offsetx;
    }
    CGFloat offsety = CGRectGetMaxY(imageRect) - CGRectGetMaxY(cropRect);
    if (offsety < 0) {
        cropRect.size.height += offsety;
    }
    
    if (_cycleMaskEnable) {
        CGContextAddEllipseInRect(context, cropRect);
    }else {
        CGContextAddRect(context, cropRect);
    }
    //反向 限制范围
    CGContextEOClip(context);
    CGContextSetFillColorWithColor(context, _cropMaskView.backgroundColor.CGColor);
    CGContextFillRect(context, contentRect);
    if (_maskImage) {
        [_maskImage drawInRect:contentRect];
    }
    UIImage *outImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return outImage;
}

- (void)touchesBegan1:(NSSet *)touches withEvent:(UIEvent *)event{
    UITouch *touch = touches.anyObject;
    CGPoint cPoint = [touch locationInView:_cropAreaView];
    for(UIView *subView in _cropAreaView.subviews) {
        if(CGRectContainsPoint(subView.frame, cPoint)) {
            _cropAreaView.userInteractionEnabled = YES;
            return;
        }
    }
    _cropAreaView.userInteractionEnabled = NO;
}
- (UIView *)hitTest:(CGPoint) point withEvent:(UIEvent *)event {
    UIView *view = [super hitTest:point withEvent:event];
    if (_showCycleLine) {
        return view;
    }
    if (!ZoomTouchRange || [view isKindOfClass:[CornerView class]]) {
        return view;
    }
    CGFloat tmpW = MID_LINE_INTERACT_WIDTH/2;
    CGFloat tmpH = MID_LINE_INTERACT_HEIGHT/2;
    CGRect tmpRect = CGRectMake(0, 0, tmpW+_cropAreaCornerWidth, tmpH+_cropAreaCornerHeight);
    
    tmpRect.origin = CGPointMake(_topLeftCorner.left-tmpW, _topLeftCorner.top-tmpH);
    if (CGRectContainsPoint(tmpRect, point)) {
        return _topLeftCorner;
    }
    tmpRect.origin = CGPointMake(_topRightCorner.left, _topRightCorner.top-tmpH);
    if (CGRectContainsPoint(tmpRect, point)) {
        return _topRightCorner;
    }
    tmpRect.origin = CGPointMake(_bottomLeftCorner.left-tmpW, _bottomLeftCorner.top);
    if (CGRectContainsPoint(tmpRect, point)) {
        return _bottomLeftCorner;
    }
    tmpRect.origin = _bottomRightCorner.origin;
    if (CGRectContainsPoint(tmpRect, point)) {
        return _bottomRightCorner;
    }
    if (view == self) {
        return nil;
    }
    return view;
}

- (UIView *)getViewWithPoint:(CGPoint)point{
    if (CGRectContainsPoint(_topMidLine.frame, point) && !_topMidLine.hidden) {
        return _topMidLine;
    }
    if (CGRectContainsPoint(_bottomMidLine.frame, point) && !_bottomMidLine.hidden) {
        return _bottomMidLine;
    }
    return nil;
}
@end


